import { isSuperAdmin } from '@/utils/auth';
import { toIconComponent } from 'kf-web-library';
import { MenuDataItem } from '@ant-design/pro-components';
import * as API from '@/services';

const checkMenuPerm = (checkAuthority: string[], userAuthority: string[]): boolean => {
  return checkAuthority.some((item) => userAuthority.includes(item));
};
/**
 * 将后台API端的菜单数据结构  API.FrontMenu 转换到 前端布局组件需要的MenuDataItem (带权限过滤)
 * @param frontMenus
 */
export const transformToMenuDataItems = (frontMenus: API.FrontMenu[], authInfo: API.AuthInfo | undefined | null): MenuDataItem[] => {
  if (!authInfo) return [];
  return frontMenus
    .map((item) => {
      const retItem = {
        ...item,
        icon: toIconComponent(item.icon),
        children: item.children ? transformToMenuDataItems(item.children, authInfo) : [],
      };

      return isSuperAdmin(authInfo) || checkMenuPerm(item.authority, authInfo.authorities) ? retItem : null;
    })
    .filter((item) => !!item) as MenuDataItem[];
};

/**
 * 将菜单转换为 Object形式的组数(key: 菜单path, value: 菜单名称)
 * @param frontMenus
 */
export const transformToMenuNamepathSet = (frontMenus: API.FrontMenu[]): { [key: string]: string } => {
  const ret = {};
  const traversal = (menus: API.FrontMenu[]) => {
    menus.forEach((item) => {
      if (item.children) {
        traversal(item.children);
      }else if (item.name && item.path) {
        ret[item.path] = item.name;
      }
    });
  };
  traversal(frontMenus);
  return ret;
};
